package com.pureland.boot.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pureland.common.utils.RequestUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * @projectName: pureland_cloud
 * @className: com.pureland.boot.config.log.WebLogAspect
 * @description: Web请求响应(请求参数/响应结果)日志切面
 * @author: tong.li
 * @createTime: 2020/10/12 9:58
 * @version: v1.0
 * @copyright: 版权所有 李彤 © 2020
 */
@Aspect
@Slf4j
public class WebLogAspect {

    /** 以 controller 包下定义的所有请求为切入点 */
    @Pointcut("execution(public * *.*.*.controller..*.*(..))")
    public void webLog() {}

    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 在切点之前织入
     * @param joinPoint
     * @throws Throwable
     */
    @Before("webLog()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 开始打印请求日志
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        // 打印请求相关参数
        log.info("================================================== Start ==================================================");
        // 打印请求 url
        log.info("URL            : {}", request.getRequestURL().toString());
        // 打印 Http method
        log.info("HTTP Method    : {}", request.getMethod());
        // 打印调用 controller 的全路径以及执行方法
        log.info("Class Method   : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
        // 打印请求的 IP
        log.info("IP             : {}", RequestUtils.getIpAddress(request));
        Object[] args = joinPoint.getArgs();
        List<Object> logArgs = new ArrayList<>();
        if(null != args && args.length>0){
            for (Object arg : args) {
                if(!(arg instanceof HttpServletRequest) && !(arg instanceof HttpServletResponse) && !(arg instanceof MultipartFile)){
                    logArgs.add(arg);
                }
            }
        }
        // 打印请求入参
        log.info("Request Args   : {}", objectMapper.writeValueAsString(logArgs));
    }

    /**
     * 在切点之后织入
     * @throws Throwable
     */
//    @After("webLog()")
//    public void doAfter() throws Throwable {
//        return;
//    }

    /**
     * 环绕
     * @param proceedingJoinPoint
     * @return
     * @throws Throwable
     */
    @Around("webLog()")
    public Object doAround(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object result = proceedingJoinPoint.proceed();
        // 打印出参
        log.info("Response Args  : {}", objectMapper.writeValueAsString(result));
        // 执行耗时
        log.info("Time-Consuming : {} ms", System.currentTimeMillis() - startTime);
        log.info("================================================== End ====================================================\n");
        return result;
    }

}
